let fs = require('fs'),
  URL = require('url');

function mkdir(paths, folderName) {
  let path = folderName;
  if (!fs.existsSync(path)) {
    fs.mkdirSync(path);
  }
  for (let i = 0; i < paths.length - 1; i++) {
    path += `${paths[i]}/`;
    if (!fs.existsSync(path)) {
      fs.mkdirSync(path);
    }
  }
}

function decompress(id) {
  if (!id) {
    console.log('har file required');
    return;
  }
  // let fileName = `${__dirname}/../temp/sketchfab.com-${id}.har`;
  let fileName = `${__dirname}/hars/${id}.har`;
  if (!fs.existsSync(fileName)) {
    console.log('har file does not exist:', fileName);
    return;
  }
  let folderName = `${__dirname}/out/${id}/`;

  let har = JSON.parse(fs.readFileSync(fileName));
  har.log.entries.forEach((entry) => {
    let { content } = entry.response;

    if (content.text) {
      let url = URL.parse(entry.request.url);
      if (url.href.indexOf('log.optimizely.com') >= 0) {
        return;
      }
      if (url.href.indexOf('www.google-analytics.com') >= 0) {
        return;
      }
      if (url.pathname.endsWith('.js') ||
        url.pathname.endsWith('.css') ||
        url.pathname.endsWith('.woff') ||
        url.pathname.endsWith('.woff2') ||
        url.pathname.endsWith('.svg') ||
        url.pathname.endsWith('.jpg') ||
        url.pathname.endsWith('.jpeg') ||
        url.pathname.endsWith('.gif') ||
        url.pathname.endsWith('.png') ||
        url.pathname.endsWith('.ttf') ||
        url.pathname.endsWith('.html') ||
        url.pathname.endsWith('.gltf') ||
        url.pathname.endsWith('.obj') ||
        url.pathname.endsWith('.bin') ||
        url.pathname.endsWith('.json') ||
        url.pathname.endsWith('.bmp') ||
        url.pathname.endsWith('.gz')) {
        // console.log(url.pathname);
        let paths = url.pathname.substr(1).split('/');
        mkdir(paths, folderName);
        if (content.encoding === 'base64') {
          fs.writeFileSync(folderName + url.pathname, Buffer.from(content.text, 'base64'));
        } else {
          fs.writeFileSync(folderName + url.pathname, content.text);
        }
      } else if (url.pathname.endsWith('embed')) {
        let paths = url.pathname.substr(1).split('/');
        mkdir(paths, folderName);
        let { text } = content;
        let prefetchedData = [
          'const prefetchedData = {};\n',
        ];
        let prefetchedDataPattern = /^\s*prefetchedData\s*\[/;
        text = text.replace(/https:\/\/media\.sketchfab\.com|https:\/\/static\.sketchfab\.com/g, '');
        text = text.replace(/\/\/cdn.optimizely.com/g, '');
        text = text.replace(/integrity=".*=="/g, '');
        text = text.replace(/ga\([- ',\w]*\);/g, '');
        text = text.replace(/i\['GoogleAnalyticsObject'\]=r/g, 'return');

        let lines = text.split('\n');
        for (let i = 0; i < lines.length; i++) {
          let line = lines[i];
          if (prefetchedDataPattern.test(line)) {
            prefetchedData.push(line.trim());
          }
          if (line.indexOf('</body>') >= 0) {
            lines.splice(i, 0, '<script src="/js/geo.js"></script>');
            break;
          }
        }

        prefetchedData.push('\nmodule.exports = prefetchedData;');

        fs.writeFileSync(`${folderName + url.pathname}.html`, lines.join('\n'));
        fs.writeFileSync(`${folderName}models/${id}/data.js`, prefetchedData.join('\n'));
      } else {
        console.log(entry.request.url, content.text);
      }
    } else {
      // console.log(entry.request.url, content);
    }
  });
}

decompress(process.argv[process.argv.length - 1]);